package com.jumper.study.admin.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumper.study.admin.dto.excel.StudentData;
import com.jumper.study.admin.dto.req.StudentSearchReq;
import com.jumper.study.admin.dto.req.StudentUpdateReq;
import com.jumper.study.admin.dto.resp.StudentResp;
import com.jumper.study.admin.service.AccountService;
import com.jumper.study.admin.service.StudentService;
import com.jumper.study.common.api.CommonPageResult;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.db.model.Account;
import com.jumper.study.db.model.Student;

import java.io.IOException;
import java.net.URLEncoder;

import jakarta.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;



@RestController
@RequestMapping("/api/backend/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private AccountService accountService;

    @PostMapping("")
    public CommonPageResult<List<StudentResp>> getList(@RequestBody StudentSearchReq req) {
        Page<Student> page = Page.of(req.getPage(), req.getLimit());
        List<Student> students = studentService.listWithAccount(page, req).getRecords();
        List<StudentResp> resp = students.stream().map(
            s -> {
                StudentResp r = new StudentResp();
                r.setId(s.getId());
                r.setAccountId(s.getAccountId());
                r.setName(s.getAccount().getName());
                r.setUsername(s.getAccount().getUsername());
                r.setNickname(s.getNickname());
                r.setAvatar(s.getAccount().getAvatar());
                r.setPhone(s.getPhone());
                r.setEmail(s.getEmail());
                r.setBirthday(s.getBirthday());
                r.setGender(s.getGender());
                r.setAddress(s.getAddress());
                r.setHobby(s.getHobby());
                r.setCreatedAt(s.getCreatedAt());
                return r;
            }
        ).toList();

        return CommonPageResult.restPage(page.getCurrent(), page.getSize(), page.getTotal(), resp);
    }

    @PostMapping("/excel")
    public void excelList(HttpServletResponse response, @RequestBody StudentSearchReq req) throws IOException {
        Page<Student> page = Page.of(req.getPage(), req.getLimit());
        List<Student> students = studentService.listWithAccount(page, req).getRecords();
        List<StudentData> excelData = students.stream().map(
            s -> new StudentData(s.getId(), s.getAccount().getUsername(), s.getAccount().getName(), s.getPhone(), s.getEmail(),
                s.getBirthday(), s.getGender(), s.getAddress(), s.getHobby())
        ).toList();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学员列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf8'"+ fileName +"'.xlsx");
        EasyExcel.write(response.getOutputStream(), StudentData.class)
            .sheet("学员列表")
            .doWrite(excelData);
    }
    
    
    @GetMapping("/{accountId}")
    public CommonResult<StudentResp> getItem(@PathVariable Long accountId) {
        Student s = studentService.getByAccountId(accountId);
        if (s == null) {
            return CommonResult.notFound();
        }
        Account account = accountService.getById(s.getAccountId());
        if (account == null) {
            return CommonResult.notFound("账号不存在");
        }
        StudentResp resp = new StudentResp();
        resp.setId(s.getId());
        resp.setAccountId(s.getAccountId());
        resp.setName(account.getName());
        resp.setUsername(account.getUsername());
        resp.setAvatar(account.getAvatar());
        resp.setNickname(s.getNickname());
        resp.setPhone(s.getPhone());
        resp.setEmail(s.getEmail());
        resp.setBirthday(s.getBirthday());
        resp.setGender(s.getGender());
        resp.setAddress(s.getAddress());
        resp.setHobby(s.getHobby());
        resp.setCreatedAt(s.getCreatedAt());
        return CommonResult.success(resp);
    }
    
    @PostMapping("/{accountId}")
    @Transactional
    public CommonResult<Boolean> update(@PathVariable Long accountId, @RequestBody @Validated StudentUpdateReq req) {
        Student student = studentService.getByAccountId(accountId);
        if (student == null) {
            return CommonResult.notFound();
        }
        Account account = accountService.getById(student.getAccountId());
        if (account == null) {
            return CommonResult.notFound();
        }
        account.setName(req.getName());
        account.setAvatar(req.getAvatar());
        boolean result = accountService.updateById(account);

        student.setPhone(req.getPhone());
        student.setEmail(req.getEmail());
        student.setBirthday(req.getBirthday());
        student.setAddress(req.getAddress());
        student.setGender(req.getGender());
        student.setHobby(req.getHobby());
        result = studentService.updateById(student);

        return CommonResult.success(result);
    }
}
